package com.hnevc.asyncokhttp3demo;

import android.content.Context;
import android.content.SharedPreferences;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Cookie;
import okhttp3.HttpUrl;

/**
 * Created by Administrator on 2017/11/5.
 */

class MyCookieJar implements okhttp3.CookieJar{

    Context mContext;

    public MyCookieJar(Context context) {
        mContext = context;
    }

    @Override
    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
        SharedPreferences sp = mContext.getSharedPreferences("cookie.sp",Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        if(cookies!=null){
            Cookie cookie = cookies.get(0);
            editor.putString("name", cookie.name());
            editor.putString("domain",cookie.domain());
            editor.putString("value",cookie.value());
            editor.putString("path",cookie.path());
            editor.commit();
        }
    }

    @Override
    public List<Cookie> loadForRequest(HttpUrl url) {
        List<Cookie> cookies= new ArrayList<Cookie>();
        SharedPreferences sp = mContext.getSharedPreferences("cookie.sp",mContext.MODE_PRIVATE);
        if(sp.getString("name",null)!=null) {
            Cookie.Builder builder = new Cookie.Builder();
            Cookie cookie = builder
                    .name(sp.getString("name",null))
                    .value(sp.getString("value",null))
                    .domain(sp.getString("domain",null))
                    .path(sp.getString("path",null))
                    .build();
            cookies.add(cookie);
        }
        return cookies;
    }
}